package com.taldh.zk.NameService;

import com.taldh.netty.common.zk.ZKclient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

public class PeerNode {

    //Zookeeper客户端
    private CuratorFramework client = null;
    private String pathRegistered = null;

    private volatile static PeerNode singleInstance = null;
    private String pathPrefix = "/test/Name/prefix-";

    public static synchronized PeerNode getInst() {
        if (null == singleInstance) {
            singleInstance = new PeerNode();
            singleInstance.client = ZKclient.instance.getClient();
            singleInstance.init();
        }
        return singleInstance;
    }

    // 初始化，在Zookeeper中创建当前的分布式节点
    public void init() {
        //使用标准的前缀，创建父节点，父节点是持久化的
        // 创建一个Znode节点
        try {
            pathRegistered = client.create()
                    .creatingParentsIfNeeded()
                    //创建一个临时顺序节点，临时节点的前缀自定义
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(pathPrefix);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        client.close();
    }

    //获取节点的编号
    public long getId() {
        String sid = null;
        if (null == pathRegistered) {
            throw new RuntimeException("节点注册失败！");
        }

        int index = pathRegistered.lastIndexOf(pathPrefix);
        if (index >= 0) {
            index += pathPrefix.length();
            sid = index <= pathRegistered.length() ? pathRegistered.substring(index) : "";
        }
        if (null == sid) {
            throw new RuntimeException("分布式节点错误");
        }
        return Long.parseLong(sid);
    }

    public static void main(String[] args) {
        PeerNode inst = getInst();
        for (int i = 0; i < 10; i++) {
            singleInstance.init();
            System.out.println(inst.getId());
        }
        inst.close();

    }
}
